package com.mediacloud.app.newsmodule.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.fastjson.JSON
import com.chinamcloud.report.ReportKit
import com.eventTrack.CDPTrackReportManager
import com.jaeger.library.StatusBarUtil
import com.mediacloud.app.assembly.util.toast
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.TvAdapter
import com.mediacloud.app.newsmodule.adaptor.TvDateAdapter
import com.mediacloud.app.newsmodule.adaptor.TvProgramAdapter
import com.mediacloud.app.newsmodule.model.ProgramListItem
import com.mediacloud.app.newsmodule.model.ProgramWeekItem
import com.mediacloud.app.newsmodule.utils.EFFECTIVETIME
import com.mediacloud.app.newsmodule.utils.KillMusicUtils
import com.mediacloud.app.newsmodule.utils.VideoAddressGet
import com.mediacloud.app.newsmodule.utils.encodeUrl
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.utils.RxUtils
import com.mediaclound.appfactnet.utils.PostJsonBody
import com.utils.LinearItemDecoration
import com.utils.TimeUtils
import com.utils.playerMap
import com.yoake.media.player.XPlayer
import com.yoake.media.player.utils.auth.URLAuth
import kotlinx.android.synthetic.main.activity_detail_tv_program.*
import org.json.JSONObject
import xyz.doikki.videoplayer.player.BaseVideoView
import xyz.doikki.videoplayer.player.VideoView

/**
 * 电视节目单详情页面
 * wy
 * */
class DetailTvProgramActivity : BaseBackActivity() {

    val tvAdapter by lazy {
        TvAdapter()
    }

    val dataAdapter by lazy {
        TvDateAdapter()
    }

    val programAdapter by lazy {
        TvProgramAdapter()
    }

    //频道数据集合
    var dataList: ArrayList<ArticleItem>? = null

    //第一次选中的默认位置
    var channelPosition = 0


    //日期选中位置
    var datePosition = 3

    var startLiveProgramDateItem: ProgramWeekItem? = null
    var endLiveProgramDateItem: ProgramWeekItem? = null

    var vmsCdnIv :String ?= ""
    var vmsCdnKey :String ?= ""
    var pauseStart = false

    var startPosition = 0L

    override fun getLayoutResID(): Int {
        return R.layout.activity_detail_tv_program
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        StatusBarUtil.setDarkMode(this)

        dataList = intent.getParcelableArrayListExtra("dataList")

        channelPosition = intent.getIntExtra("selectPosition", 0)

        vmsCdnIv = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv
        vmsCdnKey = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key

        setPlayer()

        setRecycler()

        val item =dataList!![channelPosition]
        getLiveProgramInfo(
            item.vid,
            startLiveProgramDateItem?.date,
            endLiveProgramDateItem?.date
        )
        ReportKit.escalationArticle(
            item.id.toString() + "",
            item.getTitle(),
            item.publishdate,
            item.addUser
        )
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun setRecycler() {


        recycle_tv.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        recycle_tv.addItemDecoration(
            LinearItemDecoration(
                resources.getDimension(R.dimen.dimen12).toInt(),
                resources.getDimension(R.dimen.dimen6).toInt()
            )
        )
        tvAdapter.bindToRecyclerView(recycle_tv)
        tvAdapter.selectPosition = channelPosition
        tvAdapter.setNewData(dataList)
        tvAdapter.setOnItemClickListener { adapter, view, position ->
            if (position == channelPosition) {
                return@setOnItemClickListener
            }
            val item = adapter.getItem(position) as ArticleItem
            CDPTrackReportManager.getInstance().ShortVideoClick(item,position)
            channelPosition = position
            tvAdapter.selectPosition = channelPosition

            playUrl(item)

            //此处切换下方的节目单信息
            changeChannel(position)

            tvAdapter.notifyDataSetChanged()
        }

        playUrl(dataList!![channelPosition])


        val dateList: MutableList<ProgramWeekItem> = java.util.ArrayList()
        TimeUtils.getDateListForToDayBeforeAndAfter(3).forEachIndexed { index, s ->
            val item = ProgramWeekItem()
            item.date = s

            item.title = TimeUtils.toFormat(
                s, TimeUtils.DEFAULT_YYYYMMDD_FORMAT, TimeUtils.DEFAULT_MD_DOT_FORMAT
            )

            item.week = "周" + TimeUtils.getWeekNumberStr(
                TimeUtils.getDayOfWeek(
                    s, TimeUtils.DEFAULT_YYYYMMDD_FORMAT
                )
            )
            dateList.add(item)
        }

        recycler_date.layoutManager = LinearLayoutManager(this)
        dataAdapter.bindToRecyclerView(recycler_date)
        dataAdapter.selectPosition = datePosition
        dataAdapter.setNewData(dateList)

        if (dateList.size > 0) {
            startLiveProgramDateItem = dateList[0]
            endLiveProgramDateItem = dateList[dateList.size - 1]
        }

        dataAdapter.setOnItemClickListener { adapter, view, position ->
            if (position == datePosition) {
                return@setOnItemClickListener
            }
            datePosition = position
            dataAdapter.selectPosition = datePosition

            //切换节目单
            changeProgram(datePosition)

            dataAdapter.notifyDataSetChanged()
        }

        recycler_program.layoutManager = LinearLayoutManager(this)
        programAdapter.bindToRecyclerView(recycler_program)
        programAdapter.setEmptyView(R.layout.view_empty_program, recycler_program)
        programAdapter.setOnItemClickListener { adapter, view, position ->

            val item = adapter.getItem(position) as ProgramListItem
            val status = ProgramListItem.getItemState(item)
            when (status) {
                ProgramListItem.GuideItemState.REPLAY -> {
                    if (TextUtils.isEmpty(item.url)) {
                        toast("节目单回放地址生成中")
                    } else {
                        programAdapter.selectPosition = position
                        playUrl(item.url)
                    }
                }

                ProgramListItem.GuideItemState.LIVE -> {
                    programAdapter.selectPosition = position
                    playUrl(dataList!![channelPosition])
                }
            }
            programAdapter.notifyDataSetChanged()

        }
    }

    private fun changeProgram(datePosition: Int) {
        programAdapter.selectPosition = -1
        programAdapter.setNewData(dataAdapter.data[datePosition].programList)

    }

    //获取下方的节目单信息
    @SuppressLint("NotifyDataSetChanged")
    private fun changeChannel(position: Int) {
        datePosition = 3
        dataAdapter.selectPosition = datePosition
        dataAdapter.notifyDataSetChanged()
        val item = dataList!![position]
        ReportKit.escalationArticleTime()
        ReportKit.escalationArticle(
            item.id.toString() + "",
            item.getTitle(),
            item.publishdate,
            item.addUser
        )
        getLiveProgramInfo(
            item.vid,
            startLiveProgramDateItem?.date,
            endLiveProgramDateItem?.date
        )
    }

    @SuppressLint("CheckResult")
    fun getLiveProgramInfo(sourceId: String?, startDate: String?, endDate: String?) {
        val json = HashMap<String, Any?>()
        json.put("tenantId", getString(R.string.tenantid))//租户ID
        json.put("sourceId", sourceId)//信源ID
        json.put("day", startDate)//播出日期（yyyy-MM-dd），用于指定查询日期
        json.put("dayEnd", endDate)//播出日期（yyyy-MM-dd），用于指定查询结束日期，该字段要配合day参数使用，实现按日期范围查询，最长跨度不超过90天


        DataInvokeUtil.getZiMeiTiApi()
            .getProgramInfo(json)
            .compose(RxUtils.schedulersTransformer())
            .subscribe({
                if (isFinishing) {
                    return@subscribe
                }

                var data: JSONObject? = null
                if (it.optBoolean("state")) {

                    val result = it.optJSONObject("result")
                    if (result != null) {
                        data = result.optJSONObject("data")

                    }
                }

                dataAdapter.data.forEachIndexed { index, programWeekItem ->
                    if (data != null) {
                        val programListJsonStr = data?.optString(programWeekItem.date)
                        if (!TextUtils.isEmpty(programListJsonStr)) {
                            dataAdapter.data[index].programList =
                                JSON.parseArray(programListJsonStr, ProgramListItem::class.java)

                        } else {
                            dataAdapter.data[index].programList =
                                java.util.ArrayList<ProgramListItem>()
                        }
                    } else {
                        dataAdapter.data[index].programList = java.util.ArrayList<ProgramListItem>()
                    }
                }
                dataAdapter.data.let {
                    if (it.size > 0) {
                        programAdapter.selectPosition = -1
                        programAdapter.setNewData(it[dataAdapter.selectPosition].programList)
                    } else {
                        //空数据展示

                    }
                }

            }, {
                if (isFinishing) {
                    return@subscribe
                }
                programAdapter.setNewData(ArrayList<ProgramListItem>())
            }, {

            }, {

            })
    }


    private fun setPlayer() {
        //设置播放器
        player.setPlayerType(XPlayer.VIDEO_LIVE)
        player.hideTitleBackViewWhenInNormalState()
        player.hideTitleMoreView()
        player.addOnStateChangeListener(object : BaseVideoView.OnStateChangeListener {
            override fun onPlayerStateChanged(p0: Int) {

            }

            override fun onPlayStateChanged(playState: Int) {
                when(playState){

                    VideoView.STATE_PAUSED->{
                        tvAdapter.getItem(channelPosition)?.let { CDPTrackReportManager.getInstance().LiveChannelStopPlay(it,(player.currentPosition-startPosition)/1000) }
                    }
                    VideoView.STATE_PLAYING->{
                        startPosition = player.currentPosition
                        tvAdapter.getItem(channelPosition)?.let {
                            CDPTrackReportManager.getInstance().LiveChannelStartPlay(it)
                        }
                    }

                }
            }

        })

    }

    private fun playUrl(item: ArticleItem) {
        val video = JSONObject(item.video)
        val poster = video.optString("poster")
        player.setPoster(poster, AppFactoryGlobalConfig.getDefaultImageLoadDrawable())
        player.release()
        val appCustomParams = item.appCustomParams
        appCustomParams?.let{
            val jsonObject = JSONObject(it)
            val movie = jsonObject.optJSONObject("movie")
            val path = movie.optString("livePath")
            val liveDomain = movie.optString("liveDomain")
            val liveId = movie.optString("liveId")
            val txFlag = movie.optString("txFlag")
            if (txFlag != "1"){
                val tsAddress = VideoAddressGet.getAddress(video)
                val cdnConfigEncrypt = video.optString("cdnConfigEncrypt")
                if (tsAddress != null && tsAddress.length() != 0) {
                    val line = tsAddress.optJSONObject(0)
                    var liveUrl = line.optString("url")
                    player.release()
                    player.setUrl(URLAuth.encode(
                        URLAuth.EncrptMode(cdnConfigEncrypt, vmsCdnKey, vmsCdnIv),
                        liveUrl,
                        true,
                        false
                    ))
                }
            }else{
                player.setUrl(encodeUrl(liveDomain,liveId))
            }
        }
        player.start()
    }

    private fun playUrl(playUrl: String) {
        player.release()
        player.setUrl(playUrl)
        player.start()
    }

    override fun getFitSystemWindow(): Boolean {
        return false
    }

    override fun getStatusBarColor(): Int {
        return Color.TRANSPARENT
    }

    override fun onDestroy() {
        super.onDestroy()
        player.release()
    }

    override fun onResume() {
        super.onResume()
        if (pauseStart){
            playUrl(dataList!![channelPosition])
            pauseStart = false
        }
    }

    override fun onPause() {
        super.onPause()
        pauseStart = true
    }

    override fun finish() {
        ReportKit.escalationArticleTime()
        super.finish()
    }
}